import React, { Component } from 'react';
import { connect } from 'dva';
import { produce, Draft } from 'immer';
import {
  Select,
  Button,
  Table,
  Input,
  Pagination,
  Icon,
  Modal,
  Switch,
  message,
  Form,
  Radio,
} from 'antd';
import styles from './index.css';
import { DeviceListsItem } from '@/models/connect';
import { FormComponentProps } from 'antd/es/form';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { isMenuVisible } from './../../../utils/utils';
// import { vitalSignsExportInfo } from '@/services/statistics';

import {
  getDictTypeList,
  postDictTypeAdd,
  deleteDictTypeRemove,
  putDictTypeEdit,
  getDictDataSelectByDictType,
} from '@/services/systemDevice';
import { Dispatch, AnyAction } from 'redux';
import router from 'umi/router';
import _ from 'lodash';

const { TextArea } = Input;
const { Option } = Select;
interface DictManagerPsops extends FormComponentProps {
  // dictTypeList?: DeviceListsItem;
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  form: FormComponentProps['form'];
}
interface dictManage {
  filterQueryParams: any;
  addFilterQueryParams: any;
  showModel: boolean;
  delectShowModel: boolean;
  remove: any;
  editData: any;
  addType: boolean;
  selectData: any;
  params: any;
  dictTypeList: any;
}
@connect(({ loading, systemDevice }: any) => ({
  // loading: loading.effects['systemDevice/getDictTypeList'],
  // dictTypeList: systemDevice.getDictTypeList,
}))
class dictManager extends Component<DictManagerPsops, dictManage> {
  // constructor(props: VitalSignsDetailPsops) {
  // super(props);
  // }
  state: dictManage = {
    filterQueryParams: {
      dictName: '', // 字典名称
      dictType: '', // 字典类型
      status: '', // 字典状态
      pageNum: 1,
      pageSize: 10,
    },
    addFilterQueryParams: {
      dictId: '',
    },
    remove: {
      str: '',
    },
    params: {
      dictType: 'sys_user_status',
    },
    addType: true,
    editData: {},
    showModel: false,
    delectShowModel: false,
    selectData: [],
    dictTypeList: {},
  };
  handleSubmit = (e: any) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        this.handleAdd(values);
      }
    });
  };
  // }
  handleInputDictNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 字典名称
    e.persist();
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.dictName = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleInputDictTypeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 字典类型
    e.persist();
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.dictType = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleChangeStatus = (e: string) => {
    // 字典状态
    console.log(e);
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.status = e;
      }),
    );
  };
  addHandleInputDictNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 新增字典名称
    e.persist();
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.addFilterQueryParams.dictName = e.target.value;
      }),
    );
  };
  addHandleInputDictTypeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.persist();
    // 新增字典类型
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.addFilterQueryParams.dictType = e.target.value;
      }),
    );
  };
  addHandleChangeStatus = (checked: any) => {
    // 新增字典状态
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.addFilterQueryParams.status = checked === true ? '0' : '1';
      }),
    );
    // this.setState(
    //   produce((draft: Draft<dictManage>): void => {
    //     draft.addFilterQueryParams.status = this.state.addFilterQueryParams.status === true ? '0' : '1'
    //   }),
    // );
  };
  handleInputDictNameChangeText = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 新增备注
    e.persist();
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.addFilterQueryParams.remark = e.target.value;
      }),
    );
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    // console.log(pageNum);
    localStorage.setItem('dictManagePage', pageNum);
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => isMenuVisible('system:dictType:list') && this.handleFilterQuery(),
    );
  };
  handleFilterQuery = async () => {
    // +localStorage.getItem('dictManagePage')  > 1 ? +localStorage.getItem('dictManagePage') :
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.pageNum =
          +localStorage.getItem('dictManagePage') > 1 ? +localStorage.getItem('dictManagePage') : 1;
      }),
    );
    const [err, data] = await getDictTypeList(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<dictManage>): void => {
          draft.dictTypeList = data;
        }),
      );
    }
  };
  // 删除
  handleRemove = (str: any) => {
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.remove.str = str;
        draft.delectShowModel = true;
      }),
    );
  };
  handledelete = async () => {
    //确认删除
    this.setState({ delectShowModel: false });
    const [err, data] = await deleteDictTypeRemove(this.state.remove);
    if (!err) {
      this.setState(
        produce((draft: Draft<dictManage>): void => {
          draft.delectShowModel = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<dictManage>): void => {
          draft.delectShowModel = false;
        }),
      );
    }
    isMenuVisible('system:dictType:list') && this.handleFilterQuery();
  };
  edit = (record: any) => {
    // 修改
    this.props.form.setFieldsValue({
      // dictId: this.state.editData[0].dictId,
      dictName: record.dictName,
      dictType: record.dictType,
      status: record.status,
      remark: record.remark,
    });
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.addType = false;
        draft.showModel = true;
        draft.editData = record;
      }),
    );
  };
  go = () => {
    router.goBack();
  };
  cancle = () => {
    this.setState({ showModel: false });
    this.props.form.resetFields();
  };
  // 新增
  handleAdd = async values => {
    if (this.state.addType) {
      const [err, data] = await postDictTypeAdd(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<dictManage>): void => {
            draft.showModel = false;
          }),
        );
        message.info('新增成功');
        this.props.form.resetFields();
      }
    } else {
      values.dictId = this.state.editData.dictId;
      const [err, data] = await putDictTypeEdit(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<dictManage>): void => {
            draft.showModel = false;
            // draft.dictTypeList = data;
          }),
        );
        message.info('修改成功');
        this.props.form.resetFields();
      }
    }
    isMenuVisible('system:dictType:list') && this.handleFilterQuery();
  };
  async componentWillMount() {
    const [err, data] = await getDictDataSelectByDictType(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<dictManage>): void => {
          draft.selectData = data;
        }),
      );
      isMenuVisible('system:dictType:list') && this.handleFilterQuery();
    }
  }
  componentWillReceiveProps(next: any) {
    if (next.isUpdate !== this.props.isUpdate) {
      isMenuVisible('system:dictType:list') && this.handleFilterQuery();
    }
  }
  columns: any = [
    {
      title: '字典主键',
      dataIndex: 'dictId',
      key: 'dictId',
    },
    {
      title: '字典名称',
      dataIndex: 'dictName',
      key: 'dictName',
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
      key: 'dictType',
      render: (text: any, record: any) => {
        return (
          <a
            onClick={() => {
              isMenuVisible('system:dictData:list') &&
              router.push(
                './system/dictData?type=' +
                  record.dictType +
                  '&id=' +
                  record.dictId +
                  '&dictName=' +
                  record.dictName,
              );
            }}
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: any, record: any) => {
        return text === '0' ? (
          <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
        ) : (
          <span style={{ color: '#cb3203' }}>停用</span>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'moreOutBed',
      key: 'moreOutBed',
      render: (text: any, record: any) => {
        return (
          <span className={styles.one}>
            {isMenuVisible('system:dictType:edit') && (
              <a
                onClick={() => {
                  // this.state.editData.push(record);
                  this.edit(record);
                  this.setState({ showModel: true, addType: false });
                }}
              >
                编辑
              </a>
            )}
            {isMenuVisible('system:dictType:remove') && (
              <a
                onClick={() => {
                  this.handleRemove(record.dictId);
                }}
              >
                删除
              </a>
            )}
            {/* <a>列表</a> */}
          </span>
        );
      },
    },
  ];
  render() {
    // const { dictTypeList = {} } = this.props;
    const { selectData } = this.state;
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    const formItemLayout = {
      wrapperCol: { span: 16 },
    };
    const title = this.state.addType ? '新增字典' : '修改字典';
    return (
      <div className={styles.dictM}>
        <div
          className={styles['inforAnasy-container-top']}
          style={{ paddingLeft: '0', overflow: 'hidden' }}
        >
          <div className={styles['inforAnasy-container-top-btn']}>
            {isMenuVisible('system:dictType:add') && (
              <Button
                type="link"
                onClick={() => {
                  this.setState({ showModel: true, addType: true });
                }}
              >
                <Icon type="plus" />
                新增
              </Button>
            )}

            {/* <Button
              type="link"
              onClick={() => {
                this.handleRemove(this.state.remove.str);
              }}
            >
              <Icon type="close" />
              删除
            </Button>
            <Button
              type="link"
              onClick={() => {
                this.edit();
              }}
            >
              <Icon type="form" />
              修改
            </Button> */}
          </div>
          <div style={{ clear: 'both' }}>
            <div className={styles['inforAnasy-container-top-input dev-search']}>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleInputDictNameChange}
                  addonBefore="字典名称"
                  placeholder="请输入字典名称"
                  value={this.state.filterQueryParams.dictName}
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleInputDictTypeeChange}
                  addonBefore="字典类型"
                  placeholder="请输入字典类型"
                  value={this.state.filterQueryParams.dictType}
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>字典状态</span>
                <Select
                  defaultValue=""
                  allowClear={true}
                  value={this.state.filterQueryParams.status}
                  onChange={this.handleChangeStatus}
                >
                  {_.map(selectData, (item: any, index: number) => (
                    <Option key={index} value={item.dictValue}>
                      {item.dictLabel}
                    </Option>
                  ))}
                </Select>
              </div>
              {isMenuVisible('system:dictType:list') && (
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.pageNum = 1;
                    }),
                    () => {
                      this.handleFilterQuery();
                    },
                  );
                }}
              >
                搜索
              </Button>
               )} 
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.dictName = '';
                      draft.filterQueryParams.dictType = '';
                      draft.filterQueryParams.status = undefined;
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
        </div>
        <Table
          scroll={{ y: '500px' }}
          pagination={false}
          columns={this.columns}
          // rowSelection={this.rowSelection}
          dataSource={this.state.dictTypeList.rows}
        />
        <div className="pagination-box">
          <Pagination
            onChange={this.handlePageChange}
            defaultCurrent={this.state.filterQueryParams.pageNum}
            current={this.state.filterQueryParams.pageNum}
            total={this.state.dictTypeList.total ? this.state.dictTypeList.total : 0}
          />
          <span className="pagination-title-box">
            第{this.state.filterQueryParams.pageNum}/
            {Math.ceil(
              (this.state.dictTypeList.total ? this.state.dictTypeList.total : 0) /
                this.state.filterQueryParams.pageSize,
            )}
            页 共{this.state.dictTypeList.total}条
          </span>
        </div>
        <Modal
          title="系统提示"
          visible={this.state.delectShowModel}
          className="dictDelete_box"
          onCancel={() => {
            this.setState({ delectShowModel: false });
          }}
          footer={null}
        >
          <div className="dictDelete_titlep">
            <p className="titlep">确定要删除选中数据吗？</p>
          </div>
          <div className={styles.footBtnArea}>
            <div
              style={{ marginRight: '30px' }}
              className={styles.foot_btn}
              onClick={() => {
                this.handledelete();
              }}
            >
              确定
            </div>
            <div
              className={styles.foot_btn}
              onClick={() => {
                this.setState({ delectShowModel: false });
              }}
            >
              取消
            </div>
          </div>
        </Modal>
        <Modal
          title={title}
          visible={this.state.showModel}
          className="dictModal_box"
          //   onOk={this.handleOk}
          onCancel={() => {
            this.props.form.resetFields();
            this.setState({ showModel: false });
          }}
        >
          <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
            <Form.Item {...formItemLayout} label="字典名称:">
              {getFieldDecorator('dictName', {
                rules: [
                  { required: true, message: '请输入字典名称' },
                  {
                    max: 20,
                    message: '最多输入20位中文名',
                  },
                ],
              })(<Input maxLength={20} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="字典类型:">
              {getFieldDecorator('dictType', {
                rules: [
                  { required: true, message: '请输入字典类型' },
                  {
                    max: 30,
                    message: '最多输入30位字符',
                  },
                ],
              })(<Input maxLength={30} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="状态">
              {getFieldDecorator('status', {
                initialValue: '0',
                rules: [{ required: true, message: '请选择状态' }],
              })(
                <Radio.Group>
                                  <Radio value="0">正常</Radio>
                                    <Radio value="1">停用</Radio>            
                </Radio.Group>,
              )}
                      
            </Form.Item>
            <Form.Item {...formItemLayout} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请输入备注' }],
              })(<Input />)}
            </Form.Item>
            <Form.Item wrapperCol={{ span: 18, offset: 5 }} className={styles.footBtnArea}>
              <Button
                type="primary"
                className={styles.foot_btn}
                onClick={this.handleSubmit}
                htmlType="submit"
              >
                确定
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.cancle();
                }}
                className={styles.foot_btn}
                htmlType="submit"
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default Form.create<DictManagerPsops>()(dictManager);
